<template>
  <div class="app-pro-basicLayout-content-wrap" style="margin: 0;display:flex;">
    <div class="app-pro-pages-content" style="height: calc(100vh - 60px);">
      <div class="classify-box_body-wrapper">
        <div class="submenu">
          <ul
            v-loading="ulLoading"
            element-loading-text="Loading"
            element-loading-spinner="el-icon-loading"
            element-loading-custom-class="element-loading-index-2"
          >
            <li class="submenu-itme" :class="{active: item.id === activeRole,deleteClass: item.delete}" v-for="(item,index) in roleList" :key="item.id" @click="handleRowClick(item.id,item.name)">
              <div class="submenu-itme_body-wrapper">
                <div class="submenu-itme-header">
                  <div class="submenu-itme-header-name">
                    <el-input v-if="item.show" ref="inputRef" v-model="item.name" style="width:130px" size="small" placeholder="이름을 입력하십시오." @blur="blurInput(item)" @change="changeInputName(item,index,$event)"></el-input>
                    <span v-else>{{item.name}}</span>
                  </div>
                  <div class="submenu-itme-header-tip">
                    <el-link :underline="false">
                      <el-tooltip class="item" effect="dark" content="수정" placement="top">
                        <i @click="showInput(item,index)" class="el-icon-edit"></i>
                      </el-tooltip>
                    </el-link>
                    <el-link :underline="false" style="margin-left:15px">
                      <el-tooltip class="item" effect="dark" content="삭제" placement="top">
                        <i @click.stop="deleteRole(item,index)" class="el-icon-delete"></i>
                      </el-tooltip>
                    </el-link>
                  </div>
                </div>
                <p class="submenu-itme-text">이 캐릭터는 부분적으로 관리 권한을 가지고 있습니다.</p>
              </div>
              <div class="delete-box">
                <el-button type="info" size="small" plain @click="item.delete=false">취소</el-button>
                <el-button type="danger" size="small" plain @click="handleDeleteRole(item,index)">삭제</el-button>
              </div>
            </li>
          </ul>
          <div>
            <div class="classify-box_plus" @click="addRole"><i class="el-icon-plus"></i> 추가</div>
          </div>
        </div>
      </div>
    </div>
    <div class="app-pro-pages-content" style="height: calc(100vh - 60px);flex:1;background:rgba(255,255,255,1)">
      <div class="setting-pages-content_body-wrapper" v-show="roleList.length">
        <div class="setting-pages-content_wrapper" style="margin-bottom:51px;display:flex; padding:20px;justify-content: space-around;overflow-y: auto;height:calc(100vh - 151px)" :style="{flexDirection:roleShowType===2?'column':'row'}">
          <div style="flex:1 1 auto" :style="{width:roleShowType===2?'100%':'50%'}">
            <h3>
              메뉴 권한
              <el-tooltip class="item" effect="dark" content="체크인을 하면 볼 수 있습니다." placement="top">
                <i class="el-icon-info"></i>
              </el-tooltip>
            </h3>
            <div class="tree-menu" style="margin:20px auto" v-loading="menuLoading">
              <el-tree
                :data="menuData"
                ref="menuTree"
                :class="[roleShowType===2?'horizontal':'']"
                :expand-on-click-node="false"
                :check-on-click-node="true"
                show-checkbox
                node-key="id"
                :indent="0"
                default-expand-all
                :props="{
                  children: 'children',
                  label: 'name',
                  value: 'id'
                }">
                <span class="custom-tree-node" slot-scope="{ node }">
                  <span><i :class="['icon', node.icon]"></i>{{ node.label }}</span>
                </span>
              </el-tree>
            </div>
          </div>
          <div style="flex:1 1 auto;" :style="{width:roleShowType===2?'100%':'50%'}">
            <h3>
              라우팅 권한
              <el-tooltip class="item" effect="dark" content="할 수 있는 권한을 선택" placement="top">
                <i class="el-icon-info"></i>
              </el-tooltip>
            </h3>
            <div class="tree-router" style="margin:20px auto" v-loading="routerLoading">
              <el-tree
                :data="routerData"
                ref="routerTree"
                :class="[roleShowType===2?'horizontal':'']"
                :expand-on-click-node="false"
                :check-on-click-node="true"
                show-checkbox
                node-key="id"
                default-expand-all
                :props="{
                  children: 'has_many_routes',
                  label: 'name',
                  value: 'id'
                }">
                <span class="custom-tree-node" slot-scope="{ node }">
                  <span><i :class="['icon', node.icon]"></i>{{ node.label }}</span>
                </span>
              </el-tree>
            </div>
          </div>
        </div>
        <div class="setting-pages-content_fixed">
          <el-row type="flex">
            <el-col :span="16" style="text-align:left">
              <span style="padding-right:40px"><span style="color:#000">{{activeName}}</span></span>
            </el-col>
            <el-col :span="8" style="text-align:right">
              <el-button size="small" type="success" :loading="btnLoading" @click="onSubmit">간수하다</el-button>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as roleApi from '@/api/setting/role'
import * as menuApi from '@/api/setting/menu'
import * as routerApi from '@/api/setting/router'
import { getObjectAllKey } from '@/utils'
export default {
  name: 'setting-role',
  data () {
    return {
      btnLoading: false,
      menuLoading: false,
      routerLoading: false,
      ulLoading: true,
      roleList: [],
      activeRole: 0,
      activeName: '',
      isAddRole: true,
      menuData: [],
      routerData: []
    }
  },
  computed: {
    roleShowType () {
      return this.$store.state.settings.roleShowType
    }
  },
  mounted () {
    this.getRoleList()
    const _this = this
    document.addEventListener('click', function (e) {
      if (e.target.className !== 'delete-box') {
        _this.roleList.forEach(e => {
          e.delete = false
        })
      }
    })
  },
  methods: {
    getRoleList () {
      roleApi.getRoleList().then(res => {
        this.getMenuList()
        this.getRouteCatalogs()
        this.ulLoading = false
        this.roleList = res.map(item => {
          return {
            ...item,
            show: false,
            delete: false
          }
        })
        if (this.roleList.length) {
          this.activeRole = this.roleList[0].id
          this.activeName = this.roleList[0].name
        }
      })
    },
    getMenuList () {
      menuApi.getMenuList().then(res => {
        this.menuData = res
      })
    },
    getRouteCatalogs () {
      routerApi.getRouteCatalogs().then(res => {
        this.routerData = res
      })
    },
    onSubmit () {
      this.btnLoading = true
      const menuData = {
        id: this.activeRole,
        menu_ids: JSON.stringify(this.$refs.menuTree.getCheckedKeys(true))
      }
      const routerData = {
        id: this.activeRole,
        route_ids: JSON.stringify(this.$refs.routerTree.getCheckedKeys(true))
      }
      console.log(menuData, routerData)
      const distributionRoutes = roleApi.distributionRoutes(routerData)
      const distributionMenus = roleApi.distributionMenus(menuData)
      Promise.all([distributionRoutes, distributionMenus]).then((res1, res2) => {
        this.$message({
          type: 'success',
          message: '저장에 성공함'
        })
      }).finally(() => {
        this.btnLoading = false
      })
    },
    getRoleMenus (data) {
      this.menuLoading = true
      roleApi.getRoleMenus(data).then(res => {
        this.menuLoading = false
        const checkKey = getObjectAllKey(res, 'id', 'children')
        this.$refs.menuTree.setCheckedKeys(checkKey)
      })
    },
    getRoleRoutes (data) {
      this.routerLoading = true
      roleApi.getRoleRoutes(data).then(res => {
        this.routerLoading = false
        const array = []
        res.forEach(item1 => {
          if (item1.has_many_routes.length) {
            item1.has_many_routes.forEach(item2 => {
              array.push(item2.id)
            })
          }
        })
        this.$refs.routerTree.setCheckedKeys(array)
      })
    },
    handleRowClick (id, name) {
      this.activeRole = id
      this.activeName = name
    },
    blurInput (item) {
      if (item.name === '') {
        item.show = false
        this.roleList.pop()
        this.activeRole = this.roleList[this.roleList.length - 1].id
        this.activeName = this.roleList[this.roleList.length - 1].name
        this.isAddRole = true
      } else {
        item.show = false
      }
    },
    changeInputName (item, index, val) {
      if (item.id === 0) {
        const data = {
          name: val
        }
        roleApi.createRole(data).then(res => {
          this.$set(this.roleList[index], 'show', false)
          this.$set(this.roleList[index], 'id', res.id)
        })
      } else {
        const data = {
          id: item.id,
          name: val
        }
        roleApi.updateRole(data).then(res => {
          this.$set(this.roleList[index], 'show', false)
        })
      }
      this.activeName = val
      this.isAddRole = true
    },
    showInput (item, index) {
      item.show = true
      this.isAddRole = false
      this.$nextTick(() => {
        this.$refs.inputRef[0].focus()
      })
    },
    addRole () {
      if (this.isAddRole) {
        this.isAddRole = false
        this.roleList.push({
          show: true,
          id: 0,
          name: '',
          delete: false
        })
        this.$nextTick(() => {
          this.$refs.inputRef[0].focus()
          this.activeRole = 0
        })
      }
    },
    deleteRole (item, index) {
      this.roleList.forEach(e => {
        e.delete = false
      })
      item.delete = true
    },
    handleDeleteRole (item, index) {
      roleApi.deleteRole({ id: item.id }).then(res => {
        this.roleList.splice(index, 1)
        if (this.roleList.length) {
          this.activeRole = this.roleList[0].id
          this.activeName = this.roleList[0].name
        } else {
          this.getRoleList()
        }
      })
    }
  },
  watch: {
    activeRole: {
      handler: function (val) {
        if (val !== 0) {
          this.getRoleMenus({ id: val })
          this.getRoleRoutes({ id: val })
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .element-loading-index-2 {
  z-index: 2;
  min-height: 100px;
}
</style>
